'''
Created on Feb 12, 2014

@author: yfrank
'''
import Project.Simulation.Transport.Enums as Enums

import Project.Simulation.CodingUtils.Logging as Logging


class Peer(object):
    '''
    classdocs
    '''
    def __init__(self, ch, sm):

        self.channel = ch
        self.stateMachine = sm


    def get_channel(self):
        return self.channel

    def reconnect(self,conn):
        self.stateMachine.handle_event(Enums.PeerEvent.CONN)
        self.channel=conn

    def recv_message(self):
        msg = self.channel.read()
        if len(msg) != 0:
            self.stateMachine.handle_event(Enums.PeerEvent.RECV,msg)
        else:
            self.disconnect()


    def send_message(self,msg):
        self.channel.send(msg)
        self.stateMachine.handle_event(Enums.PeerEvent.SEND,msg)


    def connect(self,addr):
        try:
            soc = None
            Logging.log("CONNECTING TO: "+str(addr))
            soc = self.channel.open_connection(addr)
            self.stateMachine.handle_event(Enums.PeerEvent.CONN)
        except Exception:
            Logging.log("FAILED TO CONNECT: "+str(addr))
        finally:
            return soc

    def disconnect(self):
        self.stateMachine.handle_event(Enums.PeerEvent.DISC)
        self.channel.close()

    def isClosed(self):
        return self.get_state() == Enums.PeerState.CLOSE

    def isOpen(self):
        return self.get_state() == Enums.PeerState.OPEN

    def isBusy(self):
        return self.get_state() == Enums.PeerState.BUSY

    def get_state(self):
        return  self.stateMachine.get_state()

    def handle_event(self,event,data=None):
        self.stateMachine.handle_event(event,data)

    def get_host(self):
        return self.channel.host


    def getRemoteAddr(self):
        return self.channel.address

    def __str__(self):
        return "<"+self.__class__.__name__+" "+str(self.channel.address)+">"
